#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__

#include <iostream>
#include <vector>
#include <unistd.h>
#include <cstdlib>
#include <sys/types.h>
#include <sys/wait.h>

// 先描述
class Channel
{
public:
    Channel(int fd, pid_t id)
        : _wfd(fd),
          _subid(id)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(_subid);
    }
    ~Channel()
    {
    }

private:
    int _wfd;
    int _subid;
    std::string _name;
};

// 再组织
class ChannelManger
{
public:
    ChannelManger()
    {
    }

    void BuildChannel(int wfd, pid_t subid)
    {
        // Channel c(wfd, subid);
        // _channels.push_back(c);
        _channels.emplace_back(wfd, subid);
    }

    ~ChannelManger()
    {
    }

private:
    std::vector<Channel> _channels;
};

static int gdefaultnum = 5;

class ProcessPool
{
public:
    ProcessPool(int process_num)
        : _process_num(process_num)
    {
    }

    void Work(int rfd)
    {
        while (true)
        {
            std::cout << "我是子进程, 我的rfd是: " << rfd << std::endl;
            sleep(1);
        }
    }

    bool Create()
    {
        for (int i = 0; i < _process_num; i++)
        {
            // 1. 创建管道
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
                return false;

            // 2. 创建子进程
            pid_t subid = fork();
            if (subid < 0)
                return false;
            else if (subid == 0)
            {
                // child
                close(pipefd[1]);
                Work(pipefd[0]);

                close(pipefd[0]);
                exit(0);
            }
            else
            {
                close(pipefd[0]);

                _cm.BuildChannel(pipefd[1], subid);
                //waitpid(subid, nullptr, 0);
                close(pipefd[1]);
                // parent
            }
        }
    }

    ~ProcessPool()
    {
    }

private:
    ChannelManger _cm;
    int _process_num;
};

#endif
